package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

@Component
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Resource
    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器开始执行");
        // 1.获取请求头中的token
        String token = request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            // 1.1不存在直接放行，交个登录拦截器处理
            return true;
        }

        // 2.基于token从Redis中获取用户对象
        String userKey = LOGIN_USER_KEY + token;
        Map<Object, Object> userHash = stringRedisTemplate.opsForHash().entries(userKey);
        // 3.判断对象是否存在
        if(userHash.isEmpty()){
            // 3.1不存在直接放行，交个登录拦截器处理
            return true;
        }
        // 4.将查询到的hash结构转为userDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userHash, new UserDTO(), false);
        // 5.存在，保存到ThreadLocal中
        UserHolder.saveUser(userDTO);

        // 6.刷新token的有效期
        stringRedisTemplate.expire(userKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
